local _ENV,_START = hf_setenv('card_king_rank',true)

local skynet = require "skynet"
local cjson  = require "cjson"
local util   = require "util"
local utils  = require "utils"
local reason = require "reason"
local sharedata = require "skynet.sharedata"
local mail_def  =  require "mail_def"
local constant  = require "constant"
local server_config = dofile(skynet.getenv("server_config"))

local table_insert = table.insert
local table_remove = table.remove
local table_sort = table.sort
local math_random = math.random
local math_floor = math.floor
local string_format = string.format

local handler = {}

function init()
    global_configs = nil
    redis_pool = 0
    gm_time = 0

    hf_set_sentinel_end(_ENV)
end

function make_rank_activity_key()
    return string_format('rank_award')
end

local function get_activity_time()
    return gm_time + util.get_now_time()
end

local function send_rank_award(awar_list)
    local mail_list = {}
    for rank,v in pairs(awar_list) do
        local mail = {}
        mail.uid = v.uid
        mail.title = mail_def.NEW_RNAK_TITLE
        local coins = math_floor(v.award_coins/100)
        mail.content = string.format(mail_def.NEW_RANK_CONTENT,rank,coins)
        mail.coins = v.award_coins
        mail.mail_type = 2
        mail.op_user = mail_def.OP_USER

        table_insert(mail_list,mail)
    end
    
    print("send_rank_award=========",tostring_r(mail_list))
    local url = constant.ADD_MAIL_URL
    R().hallsvr(1):call('.msg_handler','common_post_data',url,{award_list = mail_list})
end


function do_give_award_runner(conn)
    --每天10点发上一期的奖励
    local curr_time = get_activity_time()
    local zero_time = utils.getDayZeroTime(curr_time,false)
    local ten_time = zero_time + 10*60*60 
    print("do_give_award_runner====",curr_time,ten_time)
    if curr_time >= ten_time then --超过10点没在结算中
        print("do_give_award_runner====111")
        local key = make_rank_activity_key()
        local data = conn:lpop(key)
        if not data then
            print("pop_no_data")
            return
        end

        local award_list = {}
        local award_rank_list = cjson.decode(data)
        print("do_give_award_runner==========",key,data,tostring_r(award_rank_list))
        for rank,rank_data in pairs(award_rank_list) do
            if (rank_data.value_ex or 0) > 0 then
                local award_data = {
                    uid = rank_data.uid,
                    is_robot = rank_data.is_robot,
                    award_coins = rank_data.value_ex or 0,
                    nickname = rank_data.name
                }
                table_insert(award_list,award_data)
            end
        end

        send_rank_award(award_list) --发邮件奖励
        print("rank_list==============",tostring_r(award_list))
        billlog({op="act_rank_award",award_list = award_list})
    end
end

local function give_award_runner()
    while true do
        local conn = redis_pool:get_conn_from_pool()
        local ok,ret = xpcall(do_give_award_runner,debug.traceback,conn)
        if not ok then
            errlog(ret)
        end
        redis_pool:putback_to_pool(conn)
        
        skynet.sleep(300)
    end
end

local CMD = {}
function CMD.start()
    local redis_conf = {
        host = server_config.redis_conf.host,
        port = tonumber(server_config.redis_conf.port),
        db = tonumber(server_config.redis_conf.db),
        auth = server_config.redis_conf.auth,
    }

    redis_pool = require("redis_pool").new(redis_conf)

    skynet.fork(give_award_runner)
    skynet.dispatch('lua',function(session, source, cmd, ...)
        dbglog('rank_award_handler---->',cmd,...)
        local f = assert(handler[cmd],'rank_award_handler---->unknown cmd ' .. cmd)
        f(...)
    end)

    skynet.retpack(true)
end

function handler.save_rank_data(activity_id,rank_list)
    print("save_rank_data==========",activity_id,tostring_r(rank_list))
    local key = make_rank_activity_key()
    local conn = redis_pool:get_conn_from_pool()
    conn:lpush(key,cjson.encode(rank_list))
    redis_pool:putback_to_pool(conn)
end

function handler.set_gm_time(time)
    gm_time = time
    skynet.retpack(true)
end

function start()
    skynet.start(function()
        skynet.dispatch("lua", function(session, source, cmd, ...)
        local f = CMD[cmd]
            if f then
                f(...)
            else
                errlog("unknown cmd ",cmd)
                skynet.retpack(false)
            end
        end)

        -- sharedata.query("global_configs")
        -- global_configs = setmetatable({},{
        --     __index = function(t,k)
        --         return sharedata.query("global_configs")[k]
        --     end
        -- })
        global_configs = setmetatable({},{
            __index = function(t,k) 
                --return sharedata.query("global_configs")[k]
                return sharedata.query(k)
            end
        })
        
    end)
end

_START(function()
    print('now this card_king_rank is starting')
    init()
    start()
end)